package de.Hijack.Giuliani;

import android.util.Log;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import org.redpin.android.core.measure.WiFiReading;

/**
 * a class to export database to xml
 * @author Bastian Hinterleitner
 */
public class XmlHelper {

    public static boolean saveXml(ArrayList<WayPoint> entries, String url) {
        try{
            String fileText = "<?xml version=\"1.0\" encoding=\"iso-8859-15\" ?>";
            fileText += "\n<WayPoints>";
            fileText += new XmlHelper().getXmlList(entries);
            fileText += "\n</WayPoints>";
            save(fileText, url + ".xml");
            return true;
        }
        catch(Exception ex){
            ex.printStackTrace();
            return false;
        }
    }
    
    private String getXmlList(ArrayList<WayPoint> list){
        String str = "";
        for(WayPoint p : list){
            str += "\n\t<WayPoint lat=\""+p.getLatitudeE6()+"\" long=\""+p.getLongitudeE6()+"\" floor=\""+p.floor+"\">";
            str += "\n\t\t"+p.getDescription();
            if(p.measurement!=null){
                str += "\n\t\t<Measurement>";
                for(WiFiReading w : p.measurement.getWiFiReadings()){
                    str += "\n\t\t\t<WiFiReading";
                    str += "\n\t\t\t\tbssid=\""+w.getBssid()+"\"";
                    str += "\n\t\t\t\tssid=\""+w.getSsid()+"\"";
                    str += "\n\t\t\t\trssi=\""+w.getRssi()+"\"";
                    str += "\n\t\t\t\tinfrastructure=\""+w.isInfrastructure()+"\"";
                    str += "\n\t\t\t\twepEnabled=\""+w.isWepEnabled()+"\"";
                    str += "\n\t\t\t/>";
                }
                str += "\n\t\t</Measurement>";
            }
            str += "\n\t</WayPoint>";
        }
        return str;
    }

    /**
     * saves a textfile
     * 
     * @param str
     *            the String the textfail will contain
     * @param url
     *            the Path to the file you want to save it to
     * @return returns whether successful
     */
    public static boolean save(String str, String url) {
        try {
            FileWriter fstream = new FileWriter(url);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(str);
            out.close();
            return true;
        } catch (Exception e) {
            Log.d("Filesaving", e.getMessage());
            return false;
        }
    }

}
